<template>
  <div id="login">
    <div class="sucaihuo-container">
      <div class="demo form-bg" style="padding: 20px 0;">
        <!-- <textarea name="" id="list" cols="30" rows="10"></textarea> -->
        <div class="container">
          <el-row type="flex" class="row-bg" justify="center" align="middle">
            <el-col :span="6" :xs="16" :sm="8" :md="8" :lg="7">
              <span class="span-label">
                <b>用户登录</b>
              </span>
              <el-form
                :model="ruleForm"
                status-icon
                :rules="rules"
                ref="ruleForm"
                label-width="100px"
                class="demo-ruleForm"
                size="medium"
                :hide-required-asterisk="true"
              >
                <!-- <el-form-item label="用户登录" label-position="top" label-width="auto"></el-form-item> -->
                <el-form-item label="账号" prop="account">
                  <el-input type="text" placeholder="请输入内容" v-model="ruleForm.account" clearable></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="pwd">
                  <el-input
                    type="password"
                    v-model="ruleForm.pwd"
                    autocomplete="off"
                    show-password
                    placeholder="请输入密码"
                  ></el-input>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click.enter="submitForm('ruleForm')">提交</el-button>
                  <el-button @click="resetForm('ruleForm')">重置</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
          <!-- <div class="row">
            <div class="col-md-offset-3 col-md-6">
              <form class="form-horizontal" action="main.html" method="GET">
                <span class="heading">用户登录</span>
                <div class="form-group">
                  <input
                    type="text"
                    class="form-control"
                    id="user"
                    placeholder="请输入学号..."
                    required
                    autocomplete="off"
                  />
                  <i class="fa fa-user"></i>
                </div>
                <div class="form-group help">
                  <input
                    type="password"
                    class="form-control"
                    id="pwd"
                    placeholder="请输入密码..."
                    required
                  />
                  <i class="fa fa-lock"></i>
                </div>
                <div class="form-group">
                  <button id="btn" type="button" class="btn btn-default">登 录</button>
                </div>
              </form>
            </div>
          </div>-->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Axios from "axios";
import { getUserIP } from "../js/getUserIP.js";
let Base64 = require("js-base64").Base64;

export default {
  name: "Login",
  data() {
    return {
      // storObj: "",
      storObj: {
        flag: "EMPTY",
        loginTime: "",
        loginflag: "1",
        signFlag: "0",
        stuData: {
          stuID: "",
          stuPwd: "",
          currentIP: ""
        }
      },
      currentIP: "",
      loginTime: "",
      bodyBgImage: "url(" + require("../assets/back.jpg") + ")",
      vm: this.$options.methods,
      ruleForm: {
        account: "",
        pwd: ""
      },
      rules: {
        account: [
          { required: true, message: "账号不能为空" }
          //   { type: "text", message: "账号必须为数字值" }
        ],
        // pwd: [{ validator: validatePass, trigger: "blur" }]
        pwd: [{ required: true, message: "密码不能为空", trigger: "blur" }]
      }
    };
  },

  methods: {
    adminLoginCheck(ruleForm) {
      return true;
      Axios.post("/adminlogincheck")
        .then(function(res) {
          if (res.adminpass === ruleForm.pwd) {
            return true;
          } else {
            return false;
          }
        })
        .catch(function(err) {
          console.log(err);
        });
    },
    //校验登录时间是否超出限制，判定是否下课
    checkTimeLimit(storObj) {
      var _this = this;
      console.log(this);
      console.log(_this);
      Axios.get("/login/currenttime")
        .then(function(response) {
          // this.currentTime = response.currentTime;
          // moment(endTime).diff(moment(startTime),'minutes' )
          var duration = moment
            .duration(response.currentTime.diff(loginTime))
            .asSeconds();
            console.log("8888888888888888888888888");
          if (duration >= 60 * 100) {
            storObj.loginTime = response.currentTime;
            _this.loginTime = response.currentTime;
            localStorage.setItem(
              "storObj",
              Base64.encode(JSON.stringify(storObj))
            );
            return true;
          } else {
            alert("时间限制中，登录失败！");
            return false;
          }
        })
        .catch(function(err) {
          console.log(err);
          alert("获取服务器当前时间失败，请重试！");
          return false;
        });
    },
    checkPassIP(ruleForm, currentIP) {
      //校验密码和IP地址
      var _this = this;
      console.log(this);
      console.log(_this);
      getUserIP(function(currentIP) {
        currentIP = currentIP;
      });
      Axios.post("/login/checkpassip", {
        currentIP: currentIP,
        stuId: ruleForm.account,
        stuPwd: ruleForm.pwd
      })
        .then(function(response) {
          console.log("9999999999999999");
          if (response.flag == "true") {
            alert("登录成功");
            return true;
          } else {
            alert("登录校验失败，请在自己的机位上输入正确的账号和密码！");
            return false;
          }
        })
        .catch(function(err) {
          alert("登录校验失败，请输入正确的账号或密码！");
        });
    },
    // if (localStorage.getItem("storObj") == null) {

    //校验登录
    checkLogin(storObj, ruleForm) {
      let _this = this;
      if (localStorage.getItem("storObj") !== null) {
        //前端校验模块
        getUserIP(function(ip) {
          _this.currentIP = ip;
        });
        storObj = JSON.parse(
          JSON.stringify(Base64.decode(localStorage.getItem("storObj")))
        );
        _this.loginTime = storObj.loginTime;
        if (storObj.stuData.stuID === ruleForm.account) {
          //判定是否原账号登录
          if (
            storObj.stuData.stuPwd === ruleForm.pwd &&
            storObj.stuData.currentIP === _this.currentIP
          ) {
            //原账号登录校验
            alert("校验成功！");
            return true;
          } else {
            alert("登录校验失败，请在自己的机位上输入正确的账号和密码！");
            return false;
          }
        } else {
          if (_this.checkTimeLimit(storObj)) {
            return _this.checkPassIP(ruleForm, _this.currentIP);
          }
          return false;
        }
      } else {
        //进行服务器校验阶段
        return _this.checkPassIP(ruleForm, _this.currentIP);
      }
    },
    //提交表单
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        // var _this = this;
        // console.log(this);
        // console.log(_this);
        // console.log(vm);
        if (valid) {
          alert("submit!");
          this.$router.push("/home/");
          //管理员登录校验
          if (formName.account === "admin") {
            if (this.adminLoginCheck(this.ruleForm)) {
              this.$router.push("/adminhome/");
            }
          }
          //学生登录校验
          if (this.$options.methods.checkLogin(this.storObj, this.ruleForm)) {
            console.log(this.storObj);
            console.log(this.ruleForm);

            storObj.signFlag = "1";
            //Base64加密
            localStorage.setItem(
              "storObj",
              Base64.encode(JSON.stringify(storObj))
            );
            this.$router.push("/home/");
          } else {
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    // 进来的时候调用添加
    document.body.style.backgroundSize = "100%";
    document.body.style.backgroundImage = this.bodyBgImage;
  },
  beforeDestroy() {
    // 离开页面的时候清除
    document.body.style.backgroundImage = "";
  }

  //    methods: {
  //     $(function() {
  //       $("body").on("keydown", function() {
  //         if (event.keyCode == 13) {
  //           $("#btn").click();
  //         }
  //       });
  //       $("#user").focus();
  //     });
  //   },
};
</script>

<style scoped>
.container {
  margin-top: 110px;
}

.el-row {
  margin-top: 20px;
  margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
  background-color: #fff;
  /* display: block;
  height: 250px; */
}
.el-form-item {
  margin-top: 22px;
  margin-right: 20px;
}
.span-label {
  display: inline-block;
  padding: 10px;
}
</style>